﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
using SCCMFunc;
using System.Management;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;


namespace PushEntitle
{
    public partial class frmPushEntitle : Form
    {
        private int count;
        public bool sccmSearch;
        public frmPushEntitle()
        {
            count = 0;
            InitializeComponent();
        }





        private void CreateEXE()
        {
            //Deploy the embedded Radia file
            //This file is used to force installation of entitled software
            //This will not work for software that is not in the users ASERVICE.edm
            Assembly cAssembly = Assembly.GetExecutingAssembly();
            string[] aResources = cAssembly.GetManifestResourceNames();

            foreach (string rName in aResources)
            {
                if (rName.EndsWith(".exe"))
                {

                    string saveAsName = rName;
                    FileInfo fileInfoOutput = new FileInfo(saveAsName);
                    if (fileInfoOutput.Exists)
                    {
                        fileInfoOutput.Delete();
                    }
                    FileStream streamOutput = fileInfoOutput.OpenWrite();
                    Stream streamToFile = cAssembly.GetManifestResourceStream(rName);

                    const int size = 4096;
                    byte[] bytes = new byte[4096];
                    int numbytes;
                    while ((numbytes = streamToFile.Read(bytes, 0, size)) > 0)
                    {
                        streamOutput.Write(bytes, 0, numbytes);
                    }
                    streamOutput.Close();
                    streamToFile.Close();
                }
            }
        }

        private void PushEntitle_Load(object sender, EventArgs e)
        {
            //Deploy the embedded radia file for use.
            CreateEXE();

            //Shrink panel to not display SCCM Information on XP Computers
            this.Size = new Size(290, 422);
            string uname = PE.Var.ADuname;
            string domain = PE.Var.ADdomain;
            string password = PE.Var.ADpass;
            string ldapname = ADFunctions.ADF.FriendlyDomainToLdapDomain(domain);
            //MessageBox.Show(ldapname);
            ArrayList al = ADFunctions.ADF.EnumerateOU("OU=Enterprise Application Groups,DC=ent,DC=bhicorp,DC=com");
            foreach (string ob in al)
            {

                StringBuilder builder = new StringBuilder(ob.ToString());
                builder.Remove(0, 3);
                string newstring = builder.ToString();
                int index = newstring.IndexOf(",");
                if (index > 0)
                {
                    newstring = newstring.Substring(0, index);
                }
                cbSoftGroup.Items.Add(newstring);
            }


        }

        private void PopulateSoftware(string sname)
        {
            string uname = PE.Var.ADuname;
            string domain = PE.Var.ADdomain;
            string password = PE.Var.ADpass;
            string ldapname = ADFunctions.ADF.FriendlyDomainToLdapDomain(domain);
            //string sname = cbSoftGroup.SelectedText.ToString();
            //MessageBox.Show(sname);
            ArrayList al = ADFunctions.ADF.EnumerateOU("OU=" + sname + ",OU=Enterprise Application Groups,DC=ent,DC=bhicorp,DC=com");
            foreach (string ob in al)
            {

                StringBuilder builder = new StringBuilder(ob.ToString());
                builder.Remove(0, 3);
                string newstring = builder.ToString();
                int index = newstring.IndexOf(",");
                if (index > 0)
                {
                    newstring = newstring.Substring(0, index);
                }
                lbSoft.Items.Add(newstring);
            }


        }

        private void butSearch_Click(object sender, EventArgs e)
        {

            if(sccmSearch == true)
            {
                this.Size = new Size(580, 422);

                ShowCData(txtCname.Text.ToString());
                getEntitlements(txtCname.Text.ToString());
            }
            else
            {
                RadiaSoftW();
            }
        }
        private void RadiaSoftW()
        {
            try
            {

                this.Size = new Size(580, 422);

                ShowCData(txtCname.Text.ToString());
                lbEnt.Items.Clear();
                string cname = txtCname.Text.ToString();
                string uname = PE.Var.ADuname;
                string domain = PE.Var.ADdomain;
                string password = PE.Var.ADpass;

                SearchResultCollection rs = ADFunctions.ADF.GetInformation(cname, domain, uname, password);
                foreach (SearchResult sr in rs)
                {
                    foreach (string name in sr.Properties.PropertyNames)
                    {
                        foreach (Object entry in sr.Properties[name])
                        {

                            StringBuilder builder = new StringBuilder(entry.ToString());
                            builder.Remove(0, 3);
                            string newstring = builder.ToString();
                            int index = newstring.IndexOf(",");
                            if (index > 0)
                            {
                                newstring = newstring.Substring(0, index);
                            }
                            lbEnt.Items.Add(newstring);
                        }
                    }
                }
                lbEnt.Items.RemoveAt(0);

                //AddNamespacesToList();

            }
            catch (Exception f)
            {
                MessageBox.Show(f.ToString());
                mainStatus.Text = f.Message.ToString();
            }

        }
        private void ShowCData(string cname)
        {
            //string cOperatingSystem, cOSVersion, cOSServicePack, cADSiteName, cPhysicalMem, cFreeMem, cPageFileSize, cBootTime, cLocalTime, cSystemDir, cFreeHDSpace, cAdminAccessable;

            //WMI Instance

            string uname = "bhi-master\\" + PE.Var.ADuname;
            string acname = "\\\\" + cname;
            List<string> lCInfo = new List<string>();
            //Get WMI Data from remote host
            ConnectionOptions co = new ConnectionOptions();
            co.Username = PE.Var.ADuname;
            co.Password = PE.Var.ADpass;
            co.Authority = "ntlmdomain:BHI-MASTER";
            ManagementScope ms = new ManagementScope("\\\\" + cname.Trim() + "\\root\\CIMV2", co);
            ms.Connect();

            ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher mos = new ManagementObjectSearcher(ms, oq);
            ManagementObjectCollection moc = mos.Get();
            foreach (ManagementObject mob in moc)
            {
                //Populate List Box with data from WMI
                lCInfo.Add("Operating System: " + mob.Properties["Caption"].Value);
                lCInfo.Add("OS Version: " + mob.Properties["Version"].Value);
                lCInfo.Add("Service Pack: " + mob.Properties["ServicePackMajorVersion"].Value);
                lCInfo.Add("Total System Ram: " + mob.Properties["TotalVisibleMemorySize"].Value);
                lCInfo.Add("Total Free Ram: " + mob.Properties["FreePhysicalMemory"].Value);
                lCInfo.Add("Page File Size: " + mob.Properties["TotalSwapSpaceSize"].Value);
                lCInfo.Add("Total Virual Mem: " + mob.Properties["TotalVirtualMemorySize"].Value);
                lCInfo.Add("Last Boot Time: " + parseTime(mob.Properties["LastBootUpTime"].Value.ToString()));
                lCInfo.Add("Local Time: " + parseTime(mob.Properties["LocalDateTime"].Value.ToString()));
                lCInfo.Add("System Directory: " + mob.Properties["SystemDirectory"].Value);
                lCInfo.Add("System Drive: " + mob.Properties["SystemDrive"].Value);

                lbCInfo.DataSource = lCInfo;
                lbCInfo.ClearSelected();
                //lbCInfo.Enabled = false;
                lbCInfo.BackColor = SystemColors.Window;
                lbCInfo.ForeColor = SystemColors.WindowText;
            }


        }

        private DateTime parseTime(string time)
        {
            DateTime parsed = DateTime.MinValue;

            if (time != null && time.IndexOf('.') != -1)
            {
                string newDate = time.Substring(0, time.IndexOf('.') + 4);

                if (newDate.Length == 18)
                {
                    int y = Convert.ToInt32(newDate.Substring(0, 4));
                    int m = Convert.ToInt32(newDate.Substring(4, 2));
                    int d = Convert.ToInt32(newDate.Substring(6, 2));
                    int h = Convert.ToInt32(newDate.Substring(8, 2));
                    int mm = Convert.ToInt32(newDate.Substring(10, 2));
                    int s = Convert.ToInt32(newDate.Substring(12, 2));
                    int ms = Convert.ToInt32(newDate.Substring(15, 3));

                    //compose the new datetime object
                    parsed = new DateTime(y, m, d, h, mm, s, ms);
                }
            }
            return parsed;
        }

        private void butExit_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        private void cbSoftGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            lbSoft.Items.Clear();
            string selected = cbSoftGroup.SelectedItem.ToString();
            if (selected == "Restricted Software")
            {
                PopulateSoftware(selected);
            }
            else
            {
                if (selected == "Retired Software")
                {
                    PopulateSoftware(selected);
                }
                else
                {
                    if (selected == "Software")
                    {
                        PopulateSoftware(selected);
                    }
                    else
                    {
                        lbSoft.Items.Clear();
                    };
                };
            };
        }

        private void butEnt_Click(object sender, EventArgs e)
        {
            string status = ADFunctions.ADF.AddUserToGroup(txtCname.Text, lbSoft.SelectedItem.ToString(), PE.Var.ADuname, PE.Var.ADpass);
            MessageBox.Show(status.ToString());
        }

        private void txtCname_TextChanged(object sender, EventArgs e)
        {

        }

        private void butAbout_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Contact jd.roberson@bakerhughes.com");
        }

        private void butPush_Click(object sender, EventArgs e)
        {
            string sname = GetSName();
            PushToRadia(sname);
        }
        private void PushToRadia(string sname)
        {
            string args = txtCname.Text.ToString() + " Radskman.exe mname=Radia,dname=SOFTWARE,ask=y,autofix=y,context=m,startdir=SYSTEM,flushu=a,hreboot=y,ind=y,sendcat=y,cat=prompt,ulogon=n,cop=y,mnt=y,sname=" + sname;
            string UserName = PE.Var.ADuname;
            char[] PasswordChars = PE.Var.ADpass.ToCharArray();
            SecureString secure = new SecureString();
            
            foreach (char c in PasswordChars)
            {
                secure.AppendChar(c);
            }     
            
            Process.Start("c:\\winnt\\system32\\radntfyc.exe", args, UserName, secure, "bhi-master");
        }

        private string GetSName()
        {
            //Search Software Database to get proper name.
            string package = null;

            return package;
        }

        private void radioButton1_Click(object sender, EventArgs e)
        {
            radioButton2.Checked = !radioButton2.Checked;
            radioButton1.Checked = !radioButton1.Checked;
        }

        public void getEntitlements(string cname)
        {
            //Pull SCCM Entitlements
            mainStatus.Text = "Getting Entitlements";
            string uname = "bhi-master\\" + PE.Var.ADuname;
            string acname = "\\\\" + cname;
            List<string> lCInfo = new List<string>();
            //Get WMI Data from remote host
            ConnectionOptions co = new ConnectionOptions();
            co.Username = PE.Var.ADuname;
            co.Password = PE.Var.ADpass;
            co.Authority = "ntlmdomain:BHI-MASTER";
            
            string strTemp = "\\\\" + cname + "\\root\\ccm\\Policy\\Machine\\ActualConfig";
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(new ManagementScope(strTemp, co), new WqlObjectQuery("SELECT * from CCM_SoftwareDistribution"));

            string strSecondQueryRst = "Count = " + oSearcher.Get().Count.ToString() + "\r\n";
            mainStatus.Text = "";
            foreach (ManagementObject oInst in oSearcher.Get())
            {
                lbEnt.Items.Add(oInst.GetPropertyValue("PKG_Name").ToString());
            }

        }
        private void AddNamespacesToList()
        {
            this.mainStatus.Text = "Searching...";
            try
            {
                // Enumerate all WMI instances of 
                // __namespace WMI class.
                ManagementClass nsClass =
                    new ManagementClass(
                    new ManagementScope("root"),
                    new ManagementPath("__namespace"),
                    null);
                foreach (ManagementObject ns in
                    nsClass.GetInstances())
                {
                    this.lbSCCM.Items.
                        Add(ns["Name"].ToString());
                    count++;
                }
                this.mainStatus.Text =
                    count + " namespaces found.";
            }
            catch (ManagementException e)
            {
                this.mainStatus.Text = e.Message;
            }
        }

        private void radioButton2_Click(object sender, EventArgs e)
        {
            //Toggle Radio Buttons
            radioButton1.Checked = !radioButton1.Checked;
            radioButton2.Checked = !radioButton2.Checked;
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            
            //Populate the ListBoxes depending on the radio button selections
            if (lbEnt.Items.Count > 0)
            {
                if (radioButton1.Checked == true)
                {
                    lbEnt.Items.Clear();
                    lbSoft.Items.Clear();
                    cbSoftGroup.Text = "";
                    this.sccmSearch = true;
                    getEntitlements(txtCname.Text.ToString());
                }
                else
                {
                    lbEnt.Items.Clear();
                    lbSoft.Items.Clear();
                    cbSoftGroup.Text = "";
                    this.sccmSearch = true;
                    RadiaSoftW();
                }

            }
           
        }
    
    
    
    
    }

        

        
        
       
    
}
